Page({
  data: {
    position:'front',
    src:'',
    token:'',
    faceinfo:{},
    // 中英文映射
    map:{
      gender:{
        male:'男性',female:'女性'
      },
      expression:{
        none:'不笑', smile:'微笑', laugh:'大笑'
      },
      glasses:{
        none:'无眼镜', common:'普通眼镜', sun:'墨镜'
      },
      emotion:{
        angry:'愤怒', disgust:'厌恶', fear:'恐惧', happy:'高兴', sad:'伤心', surprise:'惊讶', neutral:'无表情', pouty: '撅嘴', grimace:'鬼脸'
      }
    }
  },
  reverse(){
    this.setData({
      position: this.data.position === 'back' ? 'front' : 'back'
    })
  },
  takePhoto(){
    // 创建相机的上下文对象
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality:'high',
      success:res => {
        this.setData({
          src:res.tempImagePath
        },() => {
          // 获取颜值信息
          this.getFaceInfo()
        })

      }
    })
  },
  choosePhoto(){
    wx.chooseImage({
      count: 1,
      sizeType:['original'],
      sourceType:['album'],
      success:res => {
        this.setData({
          src:res.tempFilePaths[0]
        },() => {
          // 获取颜值信息
          this.getFaceInfo()
        })
      }
    })
  },
  reChoose(){
    this.setData({
      src:'',
      faceinfo:{},
      token:''
    })
  },
  getFaceInfo(){
    wx.showLoading({
      title: '颜值检测中....',
    })
    // 1.发送请求，获取access_token
    wx.request({
      method:'POST',
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xFIUdGp7zGjPIhkuVVfhTMMI&client_secret=f6L1PlFGSX0hZpYeHQvgTwu27Akd3iVK',
      success:res => {
        this.setData({
          token:res.data.access_token
        },() => {
          // 2.准备参数
          const params = {
            image:'',
            image_type:'BASE64',
            face_field:'age,beauty,expression,gender,glasses,emotion'
          }
          // 读取图片数据为base64形式
          const fileManager = wx.getFileSystemManager()
          fileManager.readFile({
            filePath:this.data.src,
            encoding:'base64',
            success:res => {
              params.image = res.data
              // 3.发送请求，获取颜值信息
              wx.request({
                method:'POST',
                url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token='+this.data.token,
                header:{
                  'Content-Type':'application/json'
                },
                data:params,
                success:res => {
                  this.setData({
                    faceinfo:res.data.result.face_list[0]
                  })
                }, 
                complete: () => {
                  wx.hideLoading()
                }
              })
            }
          })
        })
      }
    })
  }
})